package com.netty.http;


import com.netty.common.MyInitializer;
import com.netty.utils.Constants;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * netty http服务器
 * @author gjj
 */
public class HttpServer {

    //绑定的端口号
    private  int PORT = Constants.HTTP_PORT;

    public  void run()  {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(4);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup);
            //利用netty零拷贝，在IO操作时使用池化的DirectBuffer
            b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            //禁用nagle算法，不等待，立即发送。
            b.childOption(ChannelOption.TCP_NODELAY, true);
            b.channel(NioServerSocketChannel.class);
            b.childHandler(new MyInitializer(new HttpServerHandler(),false,true));
            Channel ch = b.bind(PORT).sync().channel();
            ch.closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
